<template>
<div>
    <div id="amap"></div>
</div>
</template>

<script>
import Apis from '../../config/apis'
import _ from '../../config/util'
import Vue from 'vue'

import {
    Toast
} from 'mint-ui'

export default {
    name: 'AMap',
    props: {
        sid: String
    },
    data() {
        return {
            map: '', // 地图实例
            MyMarker: null,
            passedPolyline: null,
            downloadImg: '',
            scenicList: [
                {
                    id: 1,
                    lat: 23.124076,
                    lng: 113.396739,
                    title: '车陂楼'
                }, {
                    id: 2,
                    lat: 23.110559,
                    lng: 113.401179,
                    title: '东圃便利商店'
                }
            ],
            polyLines: [], // 路线
            maskBox: [],
            boxArr: [],
            // paintLine: [], // 要走的线
            // avatarPosition: [], //头像位置
            passLine:[],
            passedPolyline: null,
            lineData: {}
        }
    },
    computed:{
        // 是否微信环境
        isWeiXin(){
            return this.$store.state.isWeiXin;
        },
        avatarPosition(){
            return this.$store.state.currentPosition;
        },
        info() {
            return this.$store.state.userInfo
        }
    },
    mounted() {
        let ua = window.navigator.userAgent.toLowerCase()
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
            //   判断是微信环境，继续判断是否为小程序
            wx.miniProgram.getEnv((res) => {
                console.log('res.miniprogram:', res.miniprogram)
                if (res.miniprogram) {
                    this.registerWxApi();
                } else {
                    // this.registerWxApi();
                    this.registerH5Api();
                }
            })
        } else {
            this.registerH5Api();
        }

        // 显示详情
        window.showDetail = () => {
            // 显示详情
            this.$store.commit('setDetailPopupStatus', true)
        }
        // console.log('****message****',this.$store.state.userInfo)
        // this.getTravelLine();
    },
    methods: {
        registerWxApi() {
            // 微信jssdk注册
            _.registerJSSDK(1)
                .then(() => {
                    console.log('微信jssdk准备好了!')
                    const url =
                        'https://webapi.amap.com/maps?v=1.4.10&key=319dff1f55bf105417f400b42f61c8cc&plugin=AMap.MarkerClusterer&callback=amapCallback'
                    const jsapi = document.createElement('script')
                    jsapi.charset = 'utf-8'
                    jsapi.src = url
                    document.head.appendChild(jsapi)
                })
                .catch(err => {
                    Toast({
                        message: err
                    })
                })

            // 地图加载回调函数
            window.amapCallback = () => {
                console.log('小程序端地图准备好了!')
                // 微信sdk注册成功执行
                wx.ready(() => {
                    // _.geolocation().then(res => {
                    //     // 设置全局用户位置
                    //     this.$store.commit('setUserLocation', [
                    //         res.longitude,
                    //         res.latitude
                    //     ])
                    //     this.userLocation = [res.longitude, res.latitude]
                        // 获取全景图
                        this.mapOption()
                    // })
                })
            }
        },
        /**
         * h5环境注册地图api
         */
        registerH5Api() {
            const url =
                'https://webapi.amap.com/maps?v=1.4.10&key=319dff1f55bf105417f400b42f61c8cc&plugin=AMap.MarkerClusterer&callback=h5amapCallback'
            const jsapi = document.createElement('script')
            jsapi.charset = 'utf-8'
            jsapi.src = url
            document.head.appendChild(jsapi)
            // 地图加载回调函数
            window.h5amapCallback = () => {
                console.log('h5端地图准备好了!')
                this.mapOption()
            }
        },
         
        // 地图init
        mapOption() {
            let map = null
           
            // 实例化地图
           map = new AMap.Map('amap', {
                animateEnable: true,
                center: ["113.577431","23.07125"],
                zoom: 13,
                showLabel: false,
                resizeEnable: true,
                rotateEnable: false,
                pitchEnable: false,
                doubleClickZoom: true,
                jogEnable: true,
                // zoomEnable:false,
                // dragEnable: false
            })
             // 设置map对象
            this.map = map


            // 自定义地图样式
            map.setMapStyle('amap://styles/darkblue')
             // 设置全局map对象
            this.$store.commit('setMapObj', map)
            // 监听地图点击时事件
            map.on('click', () => {
                this.$emit('handleShowScenic')
            })
            // 监听地图平移事件
            // map.on('mapmove', () => {
            //     // 关闭详情弹框
            //     // this.$store.commit('setDetailPopupStatus', false)
            //     var z = this.map.getZoom();
            //     console.log('****zoom',z)
            // })
            this.getTravelLine().then(res=>{
                console.log('getTravelLine****',res)
                var aPolyline = new AMap.Polyline({
                    map: this.map,
                    path: res.lines,
                    // showDir:true,
                    strokeColor: "#0060FF",  //线颜色
                    // strokeOpacity: 1,     //线透明度
                    strokeWeight: 6,      //线宽
                    // strokeStyle: "solid"  //线样式
                });

                this.passedPolyline = new AMap.Polyline({
                    map: this.map,
                    path: res.goneLine,
                    strokeColor: "#AF5",  //线颜色
                    // strokeOpacity: 1,     //线透明度
                    strokeWeight: 6,      //线宽
                    // strokeStyle: "solid"  //线样式
                });
                this.initMapData()
            })
            // this.map.setFitView();
            // var zoom = this.map.getZoom() 
            // this.zooms = [zoom, 17]
            // console.log('****jjj',zoom)
        },
            
        initMapData(){
            
            // 自定义头像
            const avatar = this.info.avatar || require('../../assets/avatar.png')
              var markerContent = '' +
                '<div class="custom-avator">' +
                '   <img class="avator" src="'+ avatar +'">' +
                '</div>';

            this.MyMarker = new AMap.Marker({
                map: this.map,
                zIndex: 666,
                position: this.avatarPosition,
                offset: new AMap.Pixel(-26, -13),
                content: markerContent,
            });

            // 景区点
            const arr = this.scenicList
            for(let i = 0; i < arr.length; i++) {
                let scenicTitle = arr[i].title.length > 4 ? arr[i].title.slice(0, 4) + '...' : arr[i].title
                var item = new AMap.Marker({
                    map: this.map,
                    position: [arr[i].lng,arr[i].lat],
                    offset: new AMap.Pixel(-26, -13),
                    icon: new AMap.Icon({            
                        size: new AMap.Size(21, 21),
                        image: require('../../assets/cloud/point_local.png'),
                        imageOffset: new AMap.Pixel(0, 0)
                    }),
                    extData: {
                        id: arr[i].id
                    }
                })
                item.setLabel({
                    offset: new AMap.Pixel(-14, 16),  //设置文本标注偏移量
                    content: "<div class='info'>"+scenicTitle+"</div>", //设置文本标注内容
                    direction: 'right' //设置文本标注方位
                });

                //监听marker的点击事件
                AMap.event.addListener(item, 'click', (e) => {
                    let data =JSON.parse(JSON.stringify(e.target.getExtData()));
                    this.$emit('handleShowScenic', data)
                });
            }

            // 宝箱
            this.writeBox()
    
            this.MyMarker.on('moving',  e=> {
                // console.log('****moving',e)
                var lng = e.passedPath[e.passedPath.length-1].lng;
                var lat = e.passedPath[e.passedPath.length-1].lat;
                this.passedPolyline.setPath(e.passedPath);
                // 移动地图
                // this.map.panTo([lng,lat])
                this.map.setZoomAndCenter(16,[lng,lat])
            });
            this.MyMarker.on('movealong', e=> {
                this.$emit('clearTimer')
                console.log('****stop-last-once',this.avatarPosition,this.MyMarker);
                this.MyMarker.setPosition(this.avatarPosition)
                this.map.setFitView();
                this.$store.commit("setIsFinishRoute", true);
                this.getTravelLine()
            })

            this.map.setFitView();

            this.$store.commit('setInitMap', true)
        },
        startAnimation(lineArr, speed) {
            this.MyMarker.moveAlong(lineArr, speed);
        },
        handleBox() {
            this.$emit('handleBox')
        },
        getTravelLine(){
            var params = {
                travel_id: this.info.id,
                uid: this.info.uid
            }
            return new Promise((resolve, reject)=>{
                this.axios.post(Apis.travelLineData, params).then(res => {
                    // console.log('*****res****',res)
                    if(res.data.length == res.data.user_travel.routes_length){
                        this.$store.commit("setFoot", false) 
                    }else{
                        this.$store.commit("setFoot", true)
                    }
                    this.lineData = res.data;
                    this.scenicList = res.data.routes;
                    // 设置标题
                    window.document.title = res.data.title;
                    this.$store.commit("setLineData", res.data);
                    var stopPosition = Array.from(res.data.position);
                    this.$store.commit("setCurrentPosition", stopPosition) 
                    this.map.setCenter(stopPosition)

                    // 获取线路数据点
                    this.axios.get(res.data.steps).then(result => {
                        var lines = JSON.parse(result.data);
                        this.$store.commit("setPaintLines", lines);

                        var goneLine = [];
                        for(var i=0; i<lines.length; i++){
                            // goneLine.push(new AMap.LngLat(lines[i][0],lines[i][1]))
                            goneLine.push(lines[i])
                            if(String(stopPosition) == String(lines[i])){
                                // console.log('===========',lines[i])
                                break;
                            }
                        }

                        var allLines = {
                            lines: lines,
                            goneLine: goneLine
                        }
                        this.$store.commit("setGoneLine", goneLine)
                        resolve(allLines)
                    })
                })
            })
        },
        initPassLine(gone){
            var passedPolyline = new AMap.Polyline({
                map: this.map,
                path: gone,
                strokeColor: "#AF5",  //线颜色
                strokeWeight: 6,      //线宽
            });
        },
        initBox(steps) {
            this.writeBox(steps)
        },
        writeBox(steps) {
            // 用户未登录或未设置宝箱时宝箱不绘画
            let boxList = this.lineData.lines
            if (!boxList.length) return
            this.scenicList.map(el => {
                boxList = boxList.map(ele => {
                    ele.isShow = false
                    if (ele.sid == el.id) {
                        ele.lat = el.lat;
                        ele.lng = el.lng;
                    }
                    return ele;
                })
                return el;
            })
            let boxArr = []
            // receive为1且steps为正数时显示宝箱
            if (!steps) boxArr = boxList.filter(ele => ele.receive == 1 && ele.steps > 0);
            // console.log('原有未领取宝箱', boxArr)
            // 点击GO之后获取到的步数与数组未来状态对比
            if (steps - 0) {
                let surplusArr = boxList.filter(ele => ele.receive == 0) // 不可领取状态
                if (!surplusArr.length) return
                surplusArr = surplusArr.map(el => {
                    el.surplus = (el.steps - 0) + (steps - 0) - 1
                    if (el.surplus >= 0) {
                        el.receive = 1
                        boxArr.push(el)
                        // console.log('存在超过未来步数的步数', el)
                    }
                    return el
                })
            }
            boxArr = boxArr.filter(el => el.isShow == false)
            // console.log('过程中到点后应领取宝箱', boxArr)
            for(let i = 0; i < boxArr.length; i++) {
                const boxPoi = {
                    lat: boxArr[i].lat,
                    lng: boxArr[i].lng
                }
                var boxMarker = new AMap.Marker({
                    map: this.map,
                    position: [boxPoi.lng,boxPoi.lat],
                    offset: new AMap.Pixel(-80, -50),
                    icon: new AMap.Icon({            
                        size: new AMap.Size(75, 58),
                        image: require('../../assets/cloud/light.png'),
                        imageOffset: new AMap.Pixel(0, 0)
                    }),
                    extData: {
                        gid: boxArr[i].gid,
                        sid: boxArr[i].sid
                    }
                })
                let boxImg = require('../../assets/cloud/cloud_box.png')
                // 自定义头像
                var boxImgContent = '<img src="' + boxImg + '" class="show-box-tips">';
                var box = new AMap.Marker({
                    map: this.map,
                    position: [boxPoi.lng,boxPoi.lat],
                    offset: new AMap.Pixel(0, 0),
                    content: boxImgContent,
                    extData: {
                        gid: boxArr[i].gid,
                        sid: boxArr[i].sid
                    }
                });
                AMap.event.addListener(boxMarker, "click", (e) => {
                    let data =JSON.parse(JSON.stringify(e.target.getExtData()));
                    this.$emit('handleBox', data)
                })
                AMap.event.addListener(box, "click", (e) => {
                    let data =JSON.parse(JSON.stringify(e.target.getExtData()));
                    this.$emit('handleBox', data)
                })
                this.maskBox.push(boxMarker)
                this.boxArr.push(box)
                // 更新lineData lines的状态数据
				let lines = this.lineData.lines.map(el => {
					boxArr.map(im => {
                        if (im.sid == el.sid) {
                            el.receive = im.receive
                            el.isShow = true
                        }
                        return im
                    })
                    return el
				})
				// 赋值处理
				this.lineData.lines = lines
                this.$store.commit('setLineData', this.lineData)
                // console.log('-----------------', this.$store.state.lineData)
            }
        },
        removeReveiceBox() {
            console.log({
                mask: this.maskBox,
                box: this.boxList
            })
            this.map.remove(this.maskBox)
            this.map.remove(this.boxArr)
        }
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style lang="scss" scoped>
#amap {
    height: 100vh;
    //  height: calc(100vh-1rem);
    width: 100%;
    position: fixed;
    top: 0;
    left: 0;
}
.poster-content{
    width: 100%;
    height: 100vh;
    background: rgba(0,0,0,.7);
    position: fixed;
    left: 0;
    top: 0;
    z-index: 665;
    .bg-light{
        width: 100%;
        height: 95%;
        // border: 1px solid #f00;
        background: url('../../assets/bg-light.png') no-repeat center;
        background-size: cover;
    }
    .btn-content{
        width: 100%;
        display: flex;
        justify-content: space-around;
        position: absolute;
        top: 78vh;
        .btn{
            width: 150px;
            height: 40px;
            line-height: 40px;
            text-align: center;
            background: linear-gradient(0deg, #1498EC 0%, #48C1FF 100%);
            border-radius: 20px;
            font-size: 16px;    
            font-weight: bold;
            color: #FFFFFF;
        }
    }
}
#myCanvas{
    position: absolute;
    top: 15vh;
    left: 0;
    right: 0;
    margin: auto;
    // border: 1px solid red;
    z-index: 666;
    
}
.poster{
    position: absolute;
    top: 15vh;
    left: 0;
    right: 0;
    margin: auto;
    // border: 1px solid red;
    z-index: 6666;
}

</style>
